package cn.newhopedairy.sim.authentication;

import cn.newhopedairy.sim.applicationq.IRoleService;
import cn.newhopedairy.sim.applicationq.IUserService;
import cn.newhopedairy.sim.infrastructure.db.po.RolePo;
import cn.newhopedairy.sim.infrastructure.db.po.UserPo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Neo.Li
 * @date 2020-12-3115:51
 */
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private IUserService userService;

    @Autowired
    private IRoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询用户
        LambdaQueryWrapper<UserPo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserPo::getUsername, username);
        UserPo user = userService.getOne(wrapper);
        if (user == null) {
            throw new UsernameNotFoundException("帐号：" + username + " 不存在！");
        }
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();

        //查询拥有的角色 TODO
        List<RolePo> roles = roleService.list();
        roles.forEach(r -> {
            //security的验证规则需要ROLE_，由于数据库里存的是vip1、vip2、vip3这种值，需要加上ROLE_
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_" + r.getRoleName()));
        });
        return new User(user.getUsername(), user.getPassword(), grantedAuthorities);
    }

}